  <template>
  <div style="margin-left: 20px;margin-top: 20px">
    <div class="container">
      <el-input v-model="input" class="input-field" placeholder="请输入内容" style="width: 300px" />
      <el-button class="input-field" icon="el-icon-search" type="primary" @click="querySearch">查询</el-button>
      <el-button icon="el-icon-circle-plus" type="warning" @click="showFormxz">新增</el-button>
    </div>
    <br>

    <el-table v-loading="loading" :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" border>
      <el-table-column v-if="showColumnid" label="序号" prop="m_id" />
      <el-table-column label="标题" prop="title" />
      <el-table-column label="方案目标" prop="target" />
      <el-table-column label="状态" prop="type">
        <template v-slot="scope">
          {{ scope.row.type === 0 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="notes" />
      <el-table-column label="操作">
        <!-- 使用v-for循环渲染按钮 -->
        <template v-slot="scope">
          <el-button-group>
            <el-button icon="el-icon-edit" type="primary" @click="showEditForm(scope.row.m_id)" />
            <template v-if="scope.row.type === 0">
              <el-button icon="el-icon-circle-close" type="primary" @click="jyzt(scope.row.m_id)" />
            </template>
            <template v-if="scope.row.type === 1">
              <el-button icon="el-icon-circle-check" type="primary" @click="jyzt(scope.row.m_id)" />
            </template>
            <el-button icon="el-icon-delete" type="danger" @click="open(scope.row.m_id)" />
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <br>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[2, 5, 10, 15, 20]"
      :total="tableData.length"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :visible.sync="showForm" title="新增">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form ref="basic" :model="basic" :rules="basicInfo" size="small">
            <el-row style="padding-top:20px;">
              <el-col :span="12">
                <el-form-item label="方案标题" prop="title">
                  <el-input v-model="basic.title" placeholder="请输入方案标题" style="width:200px" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="模板类型" prop="genre">
                  <el-select v-model="basic.genre" placeholder="--请选择--" style="width: 200px">
                    <el-option label="饮食干预" value="1" />
                    <el-option label="运动干预" value="2" />
                    <el-option label="饮食与运动干预" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="方案目标" prop="goal">
                <el-input v-model="basic.goal" style="width: 500px;" type="textarea" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="notes">
                <el-input v-model="basic.notes" style="width: 500px;" type="textarea" />
              </el-form-item>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="饮食干预" name="second ">
          <el-form ref="diet" :model="diet" :rules="dietInfo" size="small">
            <el-row>
              <el-col :span="12">
                <el-form-item label="推荐食品" prop="foodName">
                  <el-select
                    v-model="diet.foodName"
                    :loading="loading"
                    :remote-method="foodNameFind"
                    filterable
                    multiple
                    placeholder="请输入关键词"
                    remote
                    reserve-keyword
                  >
                    <el-option
                      v-for="item in optionsFood"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="餐次" prop="meals">
                  <el-select v-model="diet.meals" placeholder="--请选择--" style="width: 200px">
                    <el-option label="1餐" value="1" />
                    <el-option label="2餐" value="2" />
                    <el-option label="3餐" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="膳食份量" prop="quantity">
                  <el-input v-model="diet.quantity" style="width: 550px" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="摄入量" prop="intake">
                  <el-input v-model="diet.intake" style="width: 550px" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="display: flex; justify-content: center;">
              <el-button type="primary" @click="submitFormDiet">确定</el-button>
              <el-button @click="resetDeitForm('diet')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="运动干预" name="third">
          <el-form ref="sports" :model="sports" :rules="sportsInfo" size="small">
            <el-row>
              <el-col :span="12">
                <el-form-item label="推荐运动" prop="name">
                  <el-select
                    v-model="sports.name"
                    :loading="loading"
                    :remote-method="sportsNameFind"
                    filterable
                    multiple
                    placeholder="请输入关键词"
                    remote
                    reserve-keyword
                  >
                    <el-option
                      v-for="item in optionsSports"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运动时长" prop="duration">
                  <el-input v-model="sports.duration" placeholder="请输入运动时长" style="width:200px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="运动周期" prop="cycle">
                  <el-input v-model="sports.cycle" placeholder="请输入运动周期" style="width:200px" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="消耗量" prop="consumption">
                  <el-input v-model="sports.consumption" placeholder="请输入消耗量" style="width:200px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="display: flex; justify-content: center;">
              <el-button type="primary" @click="submitFormSports('form')">确定</el-button>
              <el-button @click="resetForm('sports')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog :visible.sync="showFormxg" title="编辑">
      <el-form ref="rulexgForm" :inline="true" :model="rulexgForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="id">
              <el-input v-model="rulexgForm.id" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题" prop="bt">
              <el-input v-model="rulexgForm.bt" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="方案目标" prop="fa">
              <el-input v-model="rulexgForm.fa" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="zt">
              <el-radio-group v-model="rulexgForm.zt">
                <el-radio label="0">启用</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input v-model="rulexgForm.bz" style="width: 400px" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="display: flex; justify-content: center;">
          <el-button type="primary" @click="submitFormxg('rulexgForm')">修改</el-button>
          <el-button @click="resetFormxg('rulexgForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style>
.container {
  display: flex;
  align-items: center;
}

.input-field {
  margin-right: 10px; /* 调整元素之间的间距 */

}
</style>
<script>
import axios from 'axios'
import getters from '@/store/getters'

export default {
  data() {
    return {
      loading: false,
      input: '',
      currentPage: 1, // 当前页码
      pageSize: 2, // 每页显示的条数
      totalNum: 10, // 总条数
      activeName: 'first',
      showFormxg: false, // 控制修改表单的显示
      showForm: false, // 控制添加表单的显示状态，默认隐藏
      showColumnid: true, // 控制id数据的隐藏
      displayedData: [], // 分页后的
      optionsFood: [], // 用于存储食物选项列表
      optionsSports: [], // 用于存储运动选项列表
      tableData: [{
        m_id: 1,
        title: '心脑血管干预方案',
        genre: '方案目标',
        type: 0,
        notes: '没有备注'
      }],
      // 修改用的对象
      rulexgForm: {
        id: '',
        bt: '',
        fa: '',
        zt: '',
        bz: ''
      },
      // 添加用的对象
      basic: {
        title: '',
        genre: '',
        goal: '',
        notes: ''
      },
      diet: {
        foodName: '',
        meals: '',
        quantity: '',
        intake: ''
      },
      sports: {
        name: '',
        duration: '',
        cycle: '',
        consumption: ''
      },
      basicInfo: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        genre: [
          { required: true, message: '请选择模版类型', trigger: 'change' }
        ],
        goal: [
          { required: true, message: '请输入方案目标', trigger: 'blur' }
        ]
      },
      dietInfo: {
        foodName: [
          { required: true, message: '请输入食物名称', trigger: 'blur' }
        ],
        meals: [
          { required: true, message: '请选择餐次', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入分量', trigger: 'blur' }
        ],
        intake: [
          { required: true, message: '请输入摄入量', trigger: 'blur' }
        ]
      },
      sportsInfo: {
        name: [
          { required: true, message: '请输入运动名称', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入运动周期', trigger: 'blur' }
        ],
        cycle: [
          { required: true, message: '请输入运动时长', trigger: 'blur' }
        ],
        consumption: [
          { required: true, message: '请输入消耗量', trigger: 'blur' }
        ]
      }
    }
  },
  beforeCreate() {
    console.log('beforeCreate: 页面加载前执行方法')
    axios.get('api/TemplateManagement/queryTemplate_management').then(res => {
      console.log(res)
      this.tableData = res.data.data
      console.log(this.tableData.length)
    })
  },
  mounted() {
    this.totalNum = this.tableData.length
  },
  methods: {
    handleClick(row) {
      console.log(row)
    },
    // 远程搜索食物名称
    foodNameFind(foodName) {
      if (foodName !== '') {
        this.loading = true
        axios.get('api/TemplateManagement/queryFoodByName', { params: { foodName: foodName }})
          .then(response => {
            this.optionsFood = response.data.data.map(item => ({
              value: item.foodId,
              label: item.foodName
            }))
            this.loading = false
          })
          .catch(error => {
            console.error(error)
            this.optionsFood = []
            this.loading = false
          })
      }
    },
    // 远程搜索运动名称
    sportsNameFind(sportsName) {
      if (sportsName !== '') {
        this.loading = true
        axios.get('api/TemplateManagement/querySportsByName', { params: { sportsName: sportsName }})
          .then(response => {
            console.log(response)
            this.optionsSports = response.data.data.map(item => ({
              value: item.sportsId,
              label: item.sportsName
            }))
            this.loading = false
          })
          .catch(error => {
            console.error(error)
            this.optionsSports = []
            this.loading = false
          })
      }
    },
    // 提交饮食干预
    submitFormDiet() {
      if (this.basic.genre === '1') {
        this.$refs['basic'].validate((basic) => {
          if (basic) {
            this.$refs['diet'].validate((diet) => {
              if (diet) {
                const templateManagementDTO = {
                  title: this.basic.title,
                  genre: this.basic.genre,
                  target: this.basic.goal,
                  notes: this.basic.notes,
                  foodList: this.diet.foodName,
                  meals: this.diet.meals,
                  quantity: this.diet.quantity,
                  intake: this.diet.intake,
                  user_id: getters.user_id(this.$store.state)
                }
                axios.post('api/TemplateManagement/addTemplate_management', templateManagementDTO, {
                  headers: {
                    'Content-Type': 'application/json'
                  }
                }).then(response => {
                  // 请求成功处理逻辑
                  if (response.status === 200) {
                    this.$message.success('提交成功!')
                    // 清空表单数据
                    this.$refs['basic'].resetFields()
                    this.$refs['diet'].resetFields()
                    this.querySearch()
                  } else {
                    this.$message.error('提交失败!')
                  }
                }).catch(error => {
                  // 异常处理逻辑
                  console.error('请求出错：', error)
                })
                this.showForm = false
              } else {
                alert('error submit!!')
                return false
              }
            })
          }
        })
      } else if (this.basic.genre === '3') {
        this.submitFormDiet_exercise()
      }
    },
    // 提交运动干预
    submitFormSports() {
      if (this.basic.genre === '2') {
        this.$refs['basic'].validate((basic) => {
          if (basic) {
            this.$refs['sports'].validate((sports) => {
              if (sports) {
                const templateManagementDTO = {
                  title: this.basic.title,
                  genre: this.basic.genre,
                  target: this.basic.goal,
                  notes: this.basic.notes,
                  duration: this.sports.duration,
                  cycle: this.sports.cycle,
                  consumption: this.sports.consumption,
                  sportsList: this.sports.name,
                  user_id: getters.user_id(this.$store.state)
                }
                axios.post('api/TemplateManagement/addTemplate_management', templateManagementDTO, {
                  headers: {
                    'Content-Type': 'application/json'
                  }
                }).then(response => {
                  // 请求成功处理逻辑
                  if (response.status === 200) {
                    this.$message.success('提交成功!')
                    // 清空表单数据
                    this.$refs['basic'].resetFields()
                    this.$refs['diet'].resetFields()
                    this.querySearch()
                  } else {
                    this.$message.error('提交失败!')
                  }
                }).catch(error => {
                  // 异常处理逻辑
                  console.error('请求出错：', error)
                })
                this.showForm = false
              } else {
                alert('error submit!!')
                return false
              }
            })
          }
        })
      } else if (this.basic.genre === '3') {
        this.submitFormDiet_exercise()
      }
    },
    // 提交运动饮食干预
    submitFormDiet_exercise() {
      this.$refs['basic'].validate((basic) => {
        if (basic) {
          this.$refs['diet'].validate((diet) => {
            if (diet) {
              this.$refs['sports'].validate((sports) => {
                if (sports) {
                  const templateManagementDTO = {
                    title: this.basic.title,
                    target: this.basic.goal,
                    notes: this.basic.notes,
                    foodList: this.diet.foodName,
                    meals: this.diet.meals,
                    quantity: this.diet.quantity,
                    intake: this.diet.intake,
                    duration: this.sports.duration,
                    cycle: this.sports.cycle,
                    consumption: this.sports.consumption,
                    sportsList: this.sports.name,
                    genre: this.basic.genre,
                    user_id: getters.user_id(this.$store.state)
                  }
                  axios.post('api/TemplateManagement/addTemplate_management', templateManagementDTO, {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  }).then(response => {
                    // 请求成功处理逻辑
                    if (response.status === 200) {
                      this.$message.success('提交成功!')
                      // 清空表单数据
                      this.$refs['basic'].resetFields()
                      this.$refs['diet'].resetFields()
                      this.$refs['sports'].resetFields()
                      this.querySearch()
                    } else {
                      this.$message.error('提交失败!')
                    }
                  }).catch(error => {
                    // 异常处理逻辑
                    console.error('请求出错：', error)
                  })
                  this.showForm = false
                } else {
                  alert('error submit!!')
                  return false
                }
              })
            }
          })
        }
      })
    },
    // 禁用
    jyzt(id) {
      this.$confirm('此操作将修改使用状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击 "确定" 按钮时执行删除操作
        this.updatazt(id) // 传递 id 参数
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        })
      })
    },
    updatazt(id) {
      const data = this.tableData.find((user) => user.m_id === id)
      let flag
      if (data.type.toString() === '1') {
        flag = 0
      } else {
        flag = 1
      }
      const updateTypeById = {
        m_id: data.m_id,
        type: flag
      }
      axios.post('api/TemplateManagement/updateTypeById', updateTypeById, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        // 请求成功处理逻辑
        if (response.status === 200) {
          this.$message.success('修改成功!')
          this.querySearch()
        } else {
          this.$message.error('修改失败!')
        }
      })
        .catch(error => {
          // 异常处理逻辑
          console.error('请求出错：', error)
        })
    },
    open(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击 "确定" 按钮时执行删除操作
        this.deleteItem(id) // 传递 id 参数
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteItem(id) {
      axios.post('api/TemplateManagement/delTemplate_managementById', { m_id: id }, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        // 请求成功处理逻辑
        if (response.status === 200) {
          this.$message.success('删除成功!')
          this.querySearch()
        } else {
          this.$message.error('删除失败!')
        }
      })
        .catch(error => {
          // 异常处理逻辑
          console.error('请求出错：', error)
        })
    },
    // 当每页显示条数发生变化时触发
    handleSizeChange(val) {
      this.pageSize = val
      console.log(`每页 ${val} 条`)
    },

    // 当前页码发生变化时触发
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
    },
    // 确定修改
    submitFormxg(formName) {
      const updateIntervene = {
        m_id: this.rulexgForm.id,
        title: this.rulexgForm.bt,
        target: this.rulexgForm.fa,
        type: this.rulexgForm.zt,
        notes: this.rulexgForm.bz
      }
      axios.post('api/TemplateManagement/updateInterveneById', updateIntervene, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        // 请求成功处理逻辑
        if (response.status === 200) {
          this.$message.success('修改成功!')
          // 清空表单数据
          this.$refs['formName'].resetFields()
          this.querySearch()
        } else {
          this.$message.error('修改失败!')
        }
      })
        .catch(error => {
          // 异常处理逻辑
          console.error('请求出错：', error)
        })
      this.querySearch()
      this.showFormxg = false
    },
    // 显示添加页面
    showFormxz() {
      this.showForm = true
    },
    // 显示修改页面
    showEditForm(m_id) {
      const data = this.tableData.find((user) => user.m_id === m_id)
      this.showFormxg = true

      // 给修改页面赋值
      this.rulexgForm.id = data.m_id
      this.rulexgForm.bt = data.title
      this.rulexgForm.fa = data.target
      this.rulexgForm.bz = data.notes
      this.rulexgForm.zt = data.type.toString()
    },
    // 添加页面取消
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    resetDeitForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    // 修改页面取消
    resetFormxg(formName) {
      this.$refs[formName].resetFields()
      this.showFormxg = false
    },
    querySearch() {
      axios.get('api/TemplateManagement/queryTemplate_management', { params: { title: this.input }})
        .then(res => {
          console.log(res)
          this.tableData = res.data.data
          console.log(this.tableData.length)
        })
        .catch(error => {
          console.error('请求出错：', error)
        })
    }
  }
}

</script>
